package com.pearadmin.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.db.Entity;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Range;
import com.pearadmin.common.tools.common.TimeS;
import com.pearadmin.common.tools.secure.SecurityUtil;
import com.pearadmin.common.tools.sequence.SequenceUtil;
import com.pearadmin.common.tools.string.Convert;
import com.pearadmin.common.web.base.BaseController;
import com.pearadmin.common.web.domain.request.PageDomain;
import com.pearadmin.common.web.domain.response.Result;
import com.pearadmin.common.web.domain.response.module.ResultTable;
import com.pearadmin.common.websocket.Customersocket;
import com.pearadmin.common.websocket.User;
import com.pearadmin.common.websocket.UserDao;
import com.pearadmin.system.domain.ScLastPeopleTime;
import com.pearadmin.system.domain.ScTime;
import com.pearadmin.system.domain.SysUser;
import com.pearadmin.system.service.IScLastPeopleTimeService;
import com.pearadmin.system.service.IScTimeService;
import com.pearadmin.system.service.ISysUserService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 设置考勤时段Controller
 *
 * @author shiqiang
 * @date 2021-05-14
 */
@RestController
@RequestMapping("/face")
@Api(tags = {"人脸识别接口"})
public class ScFaceController extends BaseController {

    @Autowired
    private IScTimeService scTimeService;

    @Resource
    private ISysUserService sysUserService;

    @Autowired
    private IScLastPeopleTimeService scLastPeopleTimeService;


    @Value("${server.port}")
    private int port;

    @ResponseBody
    @GetMapping("/get_people")
    public String list(){
        UserDao dao=new UserDao(port);
        String s = dao.getPeople();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int t=TimeS.getNowS(df.format(new Date()));
        List<Entity> timeRange = dao.getTimeRange();
        for(int i=0;i<timeRange.size();i++){
            Range range = (Range) timeRange.get(i).get("range");
            if(range.contains(t)){
                boolean fl=dao.queryByLastPeopleTime(df.format(new Date()).substring(0,10),  timeRange.get(i).getStr("start"), timeRange.get(i).getStr("stop"));
                if(fl){//判断是否已经在数据库中创建本签到时间段内的记录
                    Entity str=dao.getLastPeopleTime();
                    s=s+"@"+str.getStr("text").substring(0,str.getStr("text").length()-1);
                }else{
                    s=s+"@1#1";
                }
            }
        }
        return s;
    }
    /**
     * 删除
     */
    @ResponseBody
    @PostMapping("/qd")
    public Result qd(String name) throws Exception {
        if (StringUtils.isEmpty(name)) {
            Customersocket s=new Customersocket("qk",port);
            try {
                s.send();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }else {

                if(!name.equals("Unknown")) {
                    Customersocket s=new Customersocket("add#"+name,port);
                    try {
                        s.send();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                }
            }

        return Result.decide(true);
    }
    @ResponseBody
    @RequestMapping("/book.do")
    public String book(String username,String password) throws Exception {
        String  str="{\"result\":";
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            str=str+"false}";
            return str;
        }

        UserDao dao=new UserDao(port);
        boolean flag=dao.checkLogin(username,password);
        if(flag){
            str=str+"true}";
        }else{
            str=str+"false}";
        }
        return str;
    }

    @ResponseBody
    @PostMapping("/reg.do")
    public String reg(String username,String password) {
        String  str="{\"result\":";
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            str=str+"false}";
            return str;
        }

        SysUser byUserName = sysUserService.getByUserName(username);
        if (byUserName!=null) {
            str=str+"false}";
            return str;
        }
        SysUser sysUser = new SysUser();
        sysUser.setLogin("0");
        sysUser.setEnable("1");
        sysUser.setStatus("1");
        sysUser.setUserId(SequenceUtil.makeStringId());
        sysUser.setUsername(username);
        sysUser.setDeptId("1");
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setPassword(new BCryptPasswordEncoder().encode(password));
        List<String> roles = Lists.newArrayList();
        roles.add("1309851245195821056");
        sysUserService.saveUserRole(sysUser.getUserId(),roles);
        Boolean result = sysUserService.save(sysUser);
        str=str+"true}";
        return str;
    }

    @GetMapping("/app1.jsp")
    public ModelAndView app1(HttpServletRequest request, Model model) throws UnknownHostException {
        UserDao dao=new UserDao(port);
        List<Entity> lastPeopleTime2 = dao.getLastPeopleTime2();
        if (CollectionUtil.isNotEmpty(lastPeopleTime2)) {

            String st1="",st2="",st3="",st4="",st5="",st6="";
            List<String> names = Lists.newArrayList();
            Entity eyD = lastPeopleTime2.get(0);
            st1=eyD.getStr("time");
            st2=eyD.getStr("start");
            st3=eyD.getStr("stop");
            st4=eyD.getStr("people1");
            st5=eyD.getStr("people2");
            st6=eyD.getStr("text").replaceAll("#", ",").substring(0,eyD.getStr("text").length()-1);
            String[] st66 = eyD.getStr("text").split("#");
            List lists = Arrays.asList(st66);
            names.addAll(lists);

            model.addAttribute("st1", st1);
            model.addAttribute("st2", st2);
            model.addAttribute("st3", st3);
            model.addAttribute("st4", st4);
            model.addAttribute("st5", st5);
            model.addAttribute("b", Integer.parseInt(st4)-Integer.parseInt(st5));
            model.addAttribute("st6", st6);
            model.addAttribute("names", names);

            //正序
            Collections.reverse(lastPeopleTime2);

            List<String> p1= Lists.newArrayList(),p2=Lists.newArrayList(),p3=Lists.newArrayList();
            for(Entity ey : lastPeopleTime2){
                int f=Integer.parseInt(ey.getStr("people1"))-Integer.parseInt(ey.getStr("people2"));
                p1.add(f+"");
                p2.add(ey.getStr("people2"));
                p3.add(ey.getStr("time")+" "+ey.getStr("start"));
            }
            model.addAttribute("p1", p1);
            model.addAttribute("p2", p2);
            model.addAttribute("p3", p3);
        }
        model.addAttribute("hosts", InetAddress.getLocalHost().getHostAddress()+":"+port);
        model.addAttribute("sessionId", request.getSession().getId());
        return jumpPage("console/app1");
    }

    @GetMapping("/app2.jsp")
    public ModelAndView app2()
    {
        return jumpPage("console/app2");
    }

    /**
     * 查询设置考勤时段列表
     */
    @ResponseBody
    @GetMapping("/data")
    public ResultTable list(@ModelAttribute ScTime scTime, PageDomain pageDomain)
    {
        PageInfo<ScTime> pageInfo = scTimeService.selectScTimePage(scTime,pageDomain);
        return pageTable(pageInfo.getList(),pageInfo.getTotal());
    }

    @GetMapping("/app3.jsp")
    public ModelAndView app3() {
        return jumpPage("console/app3");
    }

    /**
     * 查询记录考勤信息列表
     */
    @ResponseBody
    @GetMapping("/datalasttime")
    public ResultTable list(@ModelAttribute ScLastPeopleTime scLastPeopleTime, PageDomain pageDomain)
    {
        PageInfo<ScLastPeopleTime> pageInfo = scLastPeopleTimeService.selectScLastPeopleTimePage(scLastPeopleTime,pageDomain);
        List<ScLastPeopleTime> list = pageInfo.getList();
        for(ScLastPeopleTime sc : list){
            if (StringUtils.isNotEmpty(sc.getText())) {
                String text = sc.getText().replaceAll("#", ",");
                sc.setText(StringUtils.substring(text,0,text.length()-1));
            }
        }
        return pageTable(pageInfo.getList(),pageInfo.getTotal());
    }

    /**
     * 删除
     */
    @ResponseBody
    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable("id") Long id)
    {
        return decide(scTimeService.deleteScTimeById(id));
    }

    /**
     * 新增保存设置考勤时段
     */
    @ResponseBody
    @GetMapping("/add_time2.do")
    public Result add_time2(String  start,String stop){
        ScTime scTime = new ScTime();
        scTime.setCreateTime(LocalDateTime.now());
        scTime.setStart(start);
        scTime.setStop(stop);
        return decide(scTimeService.insertScTime(scTime));
    }

}
